<template>
  <view v-if="visible" class="poster-overlay">
    <view class="poster-panel">
      <view class="poster-header">
        <text class="poster-title">分享海报</text>
        <view class="poster-close" @click="$emit('close')">×</view>
      </view>
      
      <!-- 加载状态 -->
      <view v-if="isLoading" class="loading-container">
        <text class="loading-text">海报生成中...</text>
      </view>
      
      <!-- 错误状态 -->
      <view v-if="errorMsg" class="error-container">
        <text class="error-text">{{ errorMsg }}</text>
        <button class="retry-btn" @click="retryDraw">重试</button>
      </view>
      
      <!-- 海报内容 -->
      <view v-if="!isLoading && !errorMsg" class="poster-content">
        <view class="poster-layout">
          <!-- 左侧：Canvas 区域 -->
          <view class="canvas-section">
            <canvas 
              id="posterCanvas"
              canvas-id="posterCanvas" 
              class="poster-canvas" 
              style="width: 300px; height: 464px; background: #ffffff; border: 2px solid #e0e0e0; display: block;"
              @error="onCanvasError"
              @touchstart="onCanvasTouch"
              @load="onCanvasLoad"
            ></canvas>
            
            <!-- 如果导出成功且不是标记，显示导出的图片 -->
            <image 
              v-if="canvasImageUrl && canvasImageUrl !== imgUrl + 'a.jpg' && canvasImageUrl !== 'canvas-drawn'"
              :src="canvasImageUrl"
              class="poster-image"
              mode="aspectFit"
              style="position: absolute; top: 0; left: 0; z-index: 10;"
            ></image>
          </view>
          
          <!-- 右侧：调试信息区域 -->
          <!-- <view class="debug-section">
            <view class="debug-info">
              <text class="debug-text">Canvas状态: {{ canvasImageUrl === 'canvas-drawn' ? '已绘制(导出失败)' : canvasImageUrl ? '已导出' : '未导出' }}</text>
              <text class="debug-text">显示内容: {{ canvasImageUrl && canvasImageUrl !== imgUrl + 'a.jpg' && canvasImageUrl !== 'canvas-drawn' ? '导出图片' : 'Canvas绘制' }}</text>
              <text class="debug-text">数据: {{ data.title || '无标题' }} | {{ data.time || '无时间' }} | ¥{{ data.price || '0' }}</text>
              <button class="test-btn" @click="testCanvasDisplay">测试Canvas显示</button>
              <button class="test-btn" @click="testDefaultImage">测试默认图片</button>
              <button class="test-btn" @click="forceDrawPoster">强制绘制海报</button>
            </view>
          </view> -->
        </view>
      </view>
      
      <view class="btn-row">
        <button class="btn primary" @click="saveToAlbum" :disabled="isLoading || !!errorMsg">保存到相册</button>
        <button class="btn" @click="$emit('close')">关闭</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { watch, nextTick, ref, getCurrentInstance } from 'vue'
import { imgUrl } from '@/utils/config'
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['done', 'close'])

// 状态管理
const isLoading = ref(false)
const errorMsg = ref('')
const canvasContext = ref(null)
const showFallback = ref(false)
const canvasImageUrl = ref('') // 存储Canvas导出的图片URL

// 强制刷新状态
const forceUpdate = () => {
  console.log('强制刷新状态')
  isLoading.value = false
  errorMsg.value = ''
}

// 强制显示Canvas
const forceShowCanvas = () => {
  console.log('强制显示Canvas')
  isLoading.value = false
  errorMsg.value = ''
  showFallback.value = false
}

// 使用备用方案：直接生成图片
const generateFallbackImage = () => {
  console.log('使用备用方案：直接生成图片')
  
  // 创建一个简单的图片URL作为备用
  const fallbackImageUrl = imgUrl + 'a.jpg'
  
  // 模拟图片生成完成
  setTimeout(() => {
    canvasImageUrl.value = fallbackImageUrl
    isLoading.value = false
    errorMsg.value = ''
    console.log('备用图片生成完成')
  }, 1000)
}

// 测试Canvas显示
const testCanvasDisplay = () => {
  console.log('测试Canvas显示')
  
  const ctx = uni.createCanvasContext('posterCanvas')
  if (!ctx) {
    console.error('无法创建Canvas上下文')
    return
  }
  
  // 绘制简单的测试内容
  ctx.setFillStyle('#ff0000')
  ctx.fillRect(0, 0, 300, 464)
  
  ctx.setFillStyle('#ffffff')
  ctx.setFontSize(20)
  ctx.fillText('Canvas 测试成功', 50, 100)
  ctx.fillText('红色背景', 50, 150)
  ctx.fillText('白色文字', 50, 200)
  
  // 同步绘制
  ctx.draw(false)
  
  console.log('Canvas 测试绘制完成')
}

// 强制绘制海报
const forceDrawPoster = async () => {
  console.log('强制绘制海报')
  
  const ctx = uni.createCanvasContext('posterCanvas')
  if (!ctx) {
    console.error('无法创建Canvas上下文')
    return
  }
  
  try {
    // 清空画布
    ctx.setFillStyle('#ffffff')
    ctx.fillRect(0, 0, 300, 464)
    
    // 绘制边框
    ctx.setStrokeStyle('#e8e8e8')
    ctx.setLineWidth(1)
    ctx.strokeRect(0, 0, 300, 464)
    
    // 绘制顶部装饰条
    ctx.setFillStyle('#2196F3')
    ctx.fillRect(0, 0, 300, 8)
    
    // 绘制标题
    ctx.setFillStyle('#1976D2')
    ctx.setFontSize(22)
    ctx.fillText('北京首钢足球友谊赛', 12, 250)
    
    // 绘制时间
    ctx.setFillStyle('#333333')
    ctx.setFontSize(15)
    ctx.fillText('⏰ 活动时间：2025.08.15 ~ 2025.08.16', 12, 280)
    
    // 绘制价格
    ctx.setFillStyle('#FF5722')
    ctx.fillRect(12, 300, 100, 32)
    
    ctx.setFillStyle('#ffffff')
    ctx.setFontSize(18)
    ctx.fillText('¥ 100.00', 22, 322)
    
    // 绘制底部标识
    ctx.setFillStyle('#2196F3')
    ctx.fillRect(0, 424, 300, 40)
    
    ctx.setFillStyle('#ffffff')
    ctx.setFontSize(14)
    ctx.fillText('🏆 草源体育 · 分享海报', 12, 450)
    
    // 同步绘制
    ctx.draw(false)
    console.log('强制绘制海报完成')
    
  } catch (error) {
    console.error('强制绘制海报失败:', error)
  }
}

// 测试默认图片显示
const testDefaultImage = async () => {
  console.log('测试默认图片显示')
  
  const ctx = uni.createCanvasContext('posterCanvas')
  if (!ctx) {
    console.error('无法创建Canvas上下文')
    return
  }
  
  try {
    // 清空画布
    ctx.setFillStyle('#ffffff')
    ctx.fillRect(0, 0, 300, 464)
    
    // 尝试加载默认图片
    const defaultImgUrl = imgUrl + 'a.jpg'
    console.log('测试默认图片URL:', defaultImgUrl)
    
    const defaultImg = await loadImageWithRetry(defaultImgUrl)
    console.log('默认图片加载结果:', defaultImg)
    
    if (defaultImg && defaultImg.path) {
      const imgH = 210
      const x = 12
      const w = 300 - 24
      
      ctx.drawImage(defaultImg.path, 0, 0, defaultImg.w, defaultImg.h, x, x, w, imgH)
      console.log('默认图片绘制成功')
      
      // 添加测试文字
      ctx.setFillStyle('#000000')
      ctx.setFontSize(16)
      ctx.fillText('默认图片测试成功', 12, 250)
    } else {
      console.log('默认图片加载失败，绘制占位图')
      // 绘制占位图
      const x = 12
      const imgH = 210
      const w = 300 - 24
      
      ctx.setFillStyle('#f8f9fa')
      ctx.fillRect(x, x, w, imgH)
      
      ctx.setStrokeStyle('#2196F3')
      ctx.setLineWidth(2)
      ctx.strokeRect(x, x, w, imgH)
      
      ctx.setFillStyle('#2196F3')
      ctx.setFontSize(40)
      ctx.fillText('🏆', x + w/2 - 20, x + imgH/2 - 10)
      
      ctx.setFillStyle('#666666')
      ctx.setFontSize(16)
      ctx.fillText('占位图测试', x + w/2 - 30, x + imgH/2 + 30)
    }
    
    // 同步绘制
    ctx.draw(false)
    console.log('默认图片测试绘制完成')
    
  } catch (error) {
    console.error('默认图片测试失败:', error)
  }
}

// 强制刷新Canvas
const forceRefreshCanvas = () => {
  console.log('强制刷新Canvas')
  
  // 重新创建Canvas上下文
  const ctx = uni.createCanvasContext('posterCanvas')
  if (!ctx) {
    console.error('无法重新创建Canvas上下文')
    return
  }
  
  // 绘制一个简单的测试内容
  ctx.setFillStyle('#ff0000')
  ctx.fillRect(0, 0, 300, 464)
  
  ctx.setFillStyle('#ffffff')
  ctx.setFontSize(30)
  ctx.fillText('强制刷新测试', 50, 100)
  
  // 使用多次重试的方式
  let drawSuccess = false
  let drawAttempts = 0
  const maxDrawAttempts = 3
  
  const tryDraw = () => {
    drawAttempts++
    console.log(`强制刷新Canvas绘制尝试 (第${drawAttempts}次)`)
    
    ctx.draw(false)
    
    setTimeout(() => {
      // 验证绘制是否成功
      uni.canvasGetImageData({
        canvasId: 'posterCanvas',
        x: 0,
        y: 0,
        width: 1,
        height: 1,
        success: (res) => {
          let hasContent = false
          for (let i = 3; i < res.data.length; i += 4) {
            if (res.data[i] > 0) {
              hasContent = true
              break
            }
          }
          
          if (hasContent) {
            console.log('强制刷新Canvas验证成功')
            drawSuccess = true
            isLoading.value = false
            
            // 尝试导出
            uni.canvasToTempFilePath({
              canvasId: 'posterCanvas',
              width: 300,
              height: 464,
              destWidth: 300,
              destHeight: 464,
              success: (res) => {
                console.log('强制刷新后导出成功:', res)
                canvasImageUrl.value = res.tempFilePath
              },
              fail: (e) => {
                console.error('强制刷新后导出失败:', e)
              }
            })
          } else if (drawAttempts < maxDrawAttempts) {
            console.log('强制刷新Canvas验证失败，重试')
            setTimeout(tryDraw, 300)
          } else {
            console.log('强制刷新Canvas最终失败')
            isLoading.value = false
          }
        },
        fail: () => {
          if (drawAttempts < maxDrawAttempts) {
            setTimeout(tryDraw, 300)
          } else {
            console.log('强制刷新Canvas最终失败')
            isLoading.value = false
          }
        }
      })
    }, 300)
  }
  
  tryDraw()
}

// 测试简单Canvas绘制
const testSimpleCanvas = () => {
  console.log('开始测试简单Canvas绘制')
  const ctx = uni.createCanvasContext('posterCanvas')
  if (!ctx) {
    console.error('无法创建Canvas上下文')
    return
  }
  
  // 使用原始尺寸进行测试
  const testWidth = 300
  const testHeight = 464
  
  // 清空画布并绘制红色背景
  ctx.setFillStyle('#ff0000')
  ctx.fillRect(0, 0, testWidth, testHeight)
  
  // 绘制白色文字
  ctx.setFillStyle('#ffffff')
  ctx.setFontSize(30)
  ctx.fillText('测试Canvas', 50, 100)
  ctx.fillText('红色背景', 50, 150)
  ctx.fillText('白色文字', 50, 200)
  
  // 绘制一个简单的图形
  ctx.setFillStyle('#00ff00')
  ctx.fillRect(50, 250, 100, 100)
  
  // 同步绘制
  ctx.draw(false)
  
  console.log('简单Canvas测试绘制完成')
  isLoading.value = false
  
  // 等待后尝试导出测试
  setTimeout(() => {
    console.log('开始测试Canvas导出')
    uni.canvasToTempFilePath({
      canvasId: 'posterCanvas',
      width: testWidth,
      height: testHeight,
      destWidth: testWidth,
      destHeight: testHeight,
      success: (res) => {
        console.log('测试Canvas导出成功:', res)
        canvasImageUrl.value = res.tempFilePath
      },
      fail: (e) => {
        console.error('测试Canvas导出失败:', e)
        // 如果导出失败，使用备用方案
        const fallbackImageUrl = imgUrl + 'a.jpg'
        canvasImageUrl.value = fallbackImageUrl
      }
    })
  }, 500)
  
  console.log('简单Canvas测试开始')
}

const toHttps = (url) => {
  if (!url) return url
  // if (url.startsWith('http://')) return url.replace('http://', 'https://')
  return url
}

const loadLocalImage = (src) => {
  return new Promise((resolve, reject) => {
    if (!src) {
      console.log('图片URL为空')
      return resolve(null)
    }
    
    console.log('开始加载图片:', src)
    
    // 检查URL格式
    if (!src.startsWith('http')) {
      console.error('图片URL格式不正确:', src)
      return reject(new Error('图片URL格式不正确'))
    }
    
    // 添加超时处理
    const timeout = setTimeout(() => {
      console.error('图片加载超时:', src)
      reject(new Error('图片加载超时'))
    }, 10000) // 10秒超时
    
    uni.getImageInfo({
      src: src,
      success: (res) => {
        clearTimeout(timeout)
        console.log('图片加载成功:', res)
        resolve({ path: res.path || res.tempFilePath || src, w: res.width, h: res.height })
      },
      fail: (err) => {
        clearTimeout(timeout)
        console.error('图片加载失败:', err)
        reject(err)
      }
    })
  })
}

// 带重试的图片加载函数
const loadImageWithRetry = async (src, maxRetries = 2) => {
  for (let i = 0; i <= maxRetries; i++) {
    try {
      console.log(`尝试加载图片 (第${i + 1}次):`, src)
      const result = await loadLocalImage(src)
      if (result) {
        console.log(`图片加载成功 (第${i + 1}次):`, src)
        return result
      }
    } catch (error) {
      console.error(`图片加载失败 (第${i + 1}次):`, error)
      if (i === maxRetries) {
        throw error
      }
      // 等待一段时间后重试
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)))
    }
  }
  throw new Error('图片加载失败，已重试多次')
}

const drawMultilineText = (ctx, text, x, y, maxWidth, lineHeight, maxLines = 2) => {
  if (!text) return y
  let line = ''
  let lineCount = 0
  for (let i = 0; i < text.length; i++) {
    const testLine = line + text[i]
    const metrics = ctx.measureText(testLine)
    if (metrics.width > maxWidth && i > 0) {
      ctx.fillText(line, x, y)
      line = text[i]
      y += lineHeight
      lineCount += 1
      if (lineCount >= maxLines - 1) {
        // 最后一行加省略号
        let j = i
        let ellipsis = ''
        while (j < text.length) {
          const test = line + text[j] + '...'
          if (ctx.measureText(test).width > maxWidth) break
          line += text[j]
          j++
        }
        ctx.fillText(line + '...', x, y)
        return y
      }
    } else {
      line = testLine
    }
  }
  ctx.fillText(line, x, y)
  return y
}

const onCanvasError = (e) => {
  console.error('Canvas 错误:', e)
  errorMsg.value = 'Canvas 渲染失败，请重试'
  isLoading.value = false
}

const onCanvasTouch = () => {
  console.log('Canvas被触摸，说明Canvas已经显示')
  // 如果Canvas可以触摸，说明已经绘制完成
  if (isLoading.value) {
    console.log('Canvas已显示，强制设置isLoading为false')
    isLoading.value = false
  }
}

const onCanvasLoad = () => {
  console.log('Canvas加载完成事件触发')
  // Canvas加载完成，可以尝试导出
  if (isLoading.value) {
    console.log('Canvas加载完成，设置isLoading为false')
    isLoading.value = false
  }
}

// 添加调试函数：检查Canvas内容
const debugCanvasContent = () => {
  console.log('开始调试Canvas内容')
  uni.canvasGetImageData({
    canvasId: 'posterCanvas',
    x: 0,
    y: 0,
    width: 10,
    height: 10,
    success: (res) => {
      console.log('Canvas内容检查成功:', res)
      // 检查是否有非透明像素
      let hasContent = false
      for (let i = 3; i < res.data.length; i += 4) {
        if (res.data[i] > 0) {
          hasContent = true
          break
        }
      }
      console.log('Canvas是否有内容:', hasContent)
    },
    fail: (e) => {
      console.error('Canvas内容检查失败:', e)
    }
  })
}

// 智能检测Canvas是否真正准备好
const waitForCanvasReady = () => {
  return new Promise((resolve) => {
    let attempts = 0
    const maxAttempts = 10
    
    const checkCanvas = () => {
      attempts++
      console.log(`智能检测Canvas (第${attempts}次)`)
      
      uni.canvasGetImageData({
        canvasId: 'posterCanvas',
        x: 0,
        y: 0,
        width: 5,
        height: 5,
        success: (res) => {
          // 检查是否有内容
          let hasContent = false
          for (let i = 3; i < res.data.length; i += 4) {
            if (res.data[i] > 0) {
              hasContent = true
              break
            }
          }
          
          if (hasContent) {
            console.log('Canvas已真正准备好，可以导出')
            resolve()
          } else if (attempts < maxAttempts) {
            console.log('Canvas暂无内容，等待后重试')
            setTimeout(checkCanvas, 500)
          } else {
            console.log('Canvas检测超时，强制继续')
            resolve()
          }
        },
        fail: (e) => {
          console.log(`Canvas检测失败 (第${attempts}次):`, e)
          if (attempts < maxAttempts) {
            setTimeout(checkCanvas, 500)
          } else {
            console.log('Canvas检测超时，强制继续')
            resolve()
          }
        }
      })
    }
    
    // 延迟开始检测
    setTimeout(checkCanvas, 500)
  })
}

const retryDraw = () => {
  errorMsg.value = ''
  drawPoster()
}

const drawPoster = async () => {
  try {
    isLoading.value = true
    errorMsg.value = ''
    
    console.log('开始绘制海报，数据:', props.data)
    console.log('图片URL:', props.data.imageUrl)
    console.log('标题:', props.data.title)
    console.log('时间:', props.data.time)
    console.log('价格:', props.data.price)
    
    // 验证数据完整性
    if (!props.data || Object.keys(props.data).length === 0) {
      throw new Error('海报数据为空，无法绘制')
    }
    
    // 等待 DOM 更新
    await nextTick()
    
    // 等待 Canvas 元素准备就绪
    await new Promise(resolve => setTimeout(resolve, 200))
    
    // 获取 Canvas 上下文
    const ctx = uni.createCanvasContext('posterCanvas')
    if (!ctx) {
      throw new Error('Canvas 上下文创建失败')
    }
    
    console.log('Canvas 上下文创建成功')
    
    // 验证 Canvas 上下文
    try {
      // 尝试一个简单的绘制操作来验证上下文
      ctx.setFillStyle('#ffffff')
      ctx.fillRect(0, 0, 1, 1)
      console.log('Canvas 上下文验证成功')
    } catch (e) {
      console.error('Canvas 上下文验证失败:', e)
      throw new Error('Canvas 上下文无效')
    }
    
    // Canvas 尺寸 - 使用原始尺寸确保内容完整显示
    const width = 300
    const height = 464
    
    console.log('Canvas 使用原始尺寸:', width, height)
    
    // 记录要绘制的数据
    console.log('准备绘制的海报数据:', {
      title: props.data.title,
      time: props.data.time,
      deadline: props.data.deadline,
      address: props.data.address,
      desc: props.data.desc,
      price: props.data.price,
      imageUrl: props.data.imageUrl
    })
    
    // 清空画布并设置背景
  ctx.setFillStyle('#ffffff')
  ctx.fillRect(0, 0, width, height)
    
    // 绘制装饰性边框
    ctx.setStrokeStyle('#e8e8e8')
    ctx.setLineWidth(1)
    ctx.strokeRect(0, 0, width, height)
    
    // 绘制顶部装饰条
    ctx.setFillStyle('#2196F3')
    ctx.fillRect(0, 0, width, 8)
    
    // 绘制顶部渐变效果
    ctx.setFillStyle('#1976D2')
    ctx.fillRect(0, 8, width, 4)
    
    // 绘制主图
  let hasImage = false
    let imageDrawn = false
    
    if (props.data.imageUrl) {
  try {
        console.log('开始加载主图:', props.data.imageUrl)
        const imgInfo = await loadImageWithRetry(props.data.imageUrl)
        console.log('图片加载结果:', imgInfo)
        
    if (imgInfo && imgInfo.path) {
          const imgH = 210
          const x = 12
      const w = width - x * 2
          console.log('绘制图片，位置:', x, x, w, imgH)
          // 使用 drawImage 的 9 参数版本，确保图片正确缩放
          ctx.drawImage(imgInfo.path, 0, 0, imgInfo.w, imgInfo.h, x, x, w, imgH)
      hasImage = true
          imageDrawn = true
          console.log('主图绘制成功')
    }
  } catch (e) {
        console.error('主图加载失败:', e)
        // 使用默认图片作为占位
        try {
          console.log('使用默认图片作为占位')
          const defaultImgUrl = imgUrl + 'a.jpg'
          console.log('默认图片URL:', defaultImgUrl)
          const defaultImg = await loadImageWithRetry(defaultImgUrl)
          console.log('默认图片加载结果:', defaultImg)
          
          if (defaultImg && defaultImg.path) {
            const imgH = 210
            const x = 12
            const w = width - x * 2
            ctx.drawImage(defaultImg.path, 0, 0, defaultImg.w, defaultImg.h, x, x, w, imgH)
            hasImage = true
            imageDrawn = true
            console.log('默认图片绘制成功')
          } else {
            console.log('默认图片加载失败，path为空')
          }
        } catch (defaultError) {
          console.error('默认图片也加载失败:', defaultError)
        }
      }
    }
    
    // 如果没有绘制任何图片，则绘制美化占位图
    if (!imageDrawn) {
      console.log('没有图片被绘制，使用美化占位图')
      const x = 12
      const imgH = 210
    const w = width - x * 2
      
      // 背景渐变效果
      ctx.setFillStyle('#f8f9fa')
    ctx.fillRect(x, x, w, imgH)
      
      // 边框
      ctx.setStrokeStyle('#2196F3')
      ctx.setLineWidth(2)
      ctx.strokeRect(x, x, w, imgH)
      
      // 图标
      ctx.setFillStyle('#2196F3')
      ctx.setFontSize(40)
      ctx.fillText('🏆', x + w/2 - 20, x + imgH/2 - 10)
      
      // 提示文字
      ctx.setFillStyle('#666666')
      ctx.setFontSize(16)
      ctx.fillText('活动海报', x + w/2 - 30, x + imgH/2 + 30)
      
      console.log('绘制美化占位图完成')
    }
    
    // 绘制标题
    ctx.setFillStyle('#1976D2')
    ctx.setFontSize(22)
    let y = 12 + 210 + 30
    const title = props.data.title || '活动详情'
    console.log('绘制标题:', title, '位置:', 12, y)
    y = drawMultilineText(ctx, title, 12, y, width - 24, 26, 2) + 20
    
    // 绘制时间
    if (props.data.time) {
      ctx.setFillStyle('#333333')
      ctx.setFontSize(15)
      const timeLine = `⏰ 活动时间：${props.data.time}`
      ctx.fillText(timeLine, 12, y)
      y += 25
      console.log('绘制时间:', timeLine, '位置:', 12, y)
    }
    
    // 绘制截止时间
    if (props.data.deadline && props.data.deadline !== '暂无截止时间') {
      ctx.setFillStyle('#FF5722')
      ctx.setFontSize(15)
      ctx.fillText(`⏳ 截止时间：${props.data.deadline}`, 12, y)
      y += 25
      console.log('绘制截止时间:', props.data.deadline)
    }
    
    // 绘制地址（只有当地址不是默认占位符时才显示）
    if (props.data.address && props.data.address !== '暂无地址信息' && props.data.address.trim() !== '') {
      ctx.setFillStyle('#666666')
      ctx.setFontSize(15)
      y = drawMultilineText(ctx, `📍 地址：${props.data.address}`, 12, y, width - 24, 22, 2) + 12
      console.log('绘制地址:', props.data.address)
    }
    
    // 绘制套餐说明
    if (props.data.desc) {
      ctx.setFillStyle('#555555')
      ctx.setFontSize(13)
      y = drawMultilineText(ctx, `📋 ${props.data.desc}`, 12, y, width - 24, 20, 3) + 15
      console.log('绘制套餐说明:', props.data.desc)
    }
    
    // 绘制价格
    if (props.data.price && props.data.price !== '0.00') {
      // 价格背景
      ctx.setFillStyle('#FF5722')
      ctx.fillRect(12, y, 100, 32)
      
      // 价格文字
      ctx.setFillStyle('#ffffff')
      ctx.setFontSize(18)
      ctx.fillText(`¥ ${props.data.price}`, 20, y + 22)
      console.log('绘制价格:', props.data.price)
    }
    
    // 绘制底部装饰条
    ctx.setFillStyle('#2196F3')
    ctx.fillRect(0, height - 40, width, 40)
    
    // 绘制底部标识
    ctx.setFillStyle('#ffffff')
    ctx.setFontSize(14)
    ctx.fillText('🏆 草源体育 · 分享海报', 12, height - 20)
    
        console.log('所有绘制操作完成，开始调用 ctx.draw()')
    
    // 关键修复：使用多次绘制确保内容渲染
    console.log('开始多次绘制确保内容渲染')
    
    // 第一次绘制
    ctx.draw(false)
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 第二次绘制
    ctx.draw(false)
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 第三次绘制
    ctx.draw(false)
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    console.log('Canvas 多次绘制完成')
    
    // 设置加载完成状态
    isLoading.value = false
    console.log('Canvas 绘制完成，开始导出')
    
    // 简化导出逻辑，直接尝试导出
    console.log('开始导出Canvas')
    
    try {
      await new Promise((resolve, reject) => {
        setTimeout(() => {
    uni.canvasToTempFilePath({
      canvasId: 'posterCanvas',
            width: 300,
            height: 464,
            destWidth: 300,
            destHeight: 464,
            success: (res) => {
              console.log('Canvas导出成功:', res)
              canvasImageUrl.value = res.tempFilePath
              emit('done', res.tempFilePath)
              resolve(res)
            },
            fail: (e) => {
              console.log('Canvas导出失败:', e)
              reject(e)
            }
          })
        }, 2000) // 等待2秒后导出
      })
    } catch (e) {
      console.log('Canvas导出失败，但内容已绘制，用户可以看到海报')
      canvasImageUrl.value = 'canvas-drawn'
      emit('done', null)
    }
    
  } catch (error) {
    console.error('海报绘制失败:', error)
    errorMsg.value = '海报绘制失败：' + error.message
    isLoading.value = false
  }
}

watch(() => props.visible, async (v) => {
  if (v) {
    console.log('海报弹层显示，开始绘制')
    // 防止重复调用
    if (isLoading.value) {
      console.log('正在绘制中，跳过重复调用')
      return
    }
    
    // 重置状态
    isLoading.value = true
    errorMsg.value = ''
    canvasImageUrl.value = ''
    
    // 等待 DOM 完全准备好
    await nextTick()
    await new Promise(resolve => setTimeout(resolve, 300))
    
    console.log('DOM准备完成，开始绘制')
      drawPoster()
  } else {
    // 弹层关闭时重置状态
    isLoading.value = false
    errorMsg.value = ''
    canvasImageUrl.value = ''
  }
})

const ensureAlbumAuth = () => new Promise((resolve, reject) => {
  uni.getSetting({
    success: (setting) => {
      const hasAuth = setting.authSetting && setting.authSetting['scope.writePhotosAlbum']
      if (hasAuth) return resolve(true)
      uni.authorize({
        scope: 'scope.writePhotosAlbum',
        success: () => resolve(true),
        fail: reject
      })
    },
    fail: reject
  })
})

const saveToAlbum = async () => {
  if (isLoading.value || errorMsg.value) {
    uni.showToast({ title: '请等待海报生成完成', icon: 'none' })
    return
  }
  
  try {
    console.log('开始保存到相册')
    
    // 显示加载提示
    uni.showLoading({ title: '正在保存...' })
    
    // 使用 Promise 包装 canvasToTempFilePath，添加重试机制
    const res = await new Promise((resolve, reject) => {
      const tryExport = (attempt = 1) => {
        console.log(`保存到相册 - 导出尝试 (第${attempt}次)`)
  uni.canvasToTempFilePath({
    canvasId: 'posterCanvas',
          width: 300,
          height: 464,
          destWidth: 300,
          destHeight: 464,
          success: (result) => {
            console.log('Canvas导出成功:', result)
            resolve(result)
          },
          fail: (e) => {
            console.error(`保存到相册 - 导出尝试 ${attempt} 失败:`, e)
            if (attempt < 3 && e.errMsg && e.errMsg.includes('canvas is empty')) {
              console.log(`Canvas为空，等待后重试 (${attempt + 1}/3)`)
              setTimeout(() => tryExport(attempt + 1), 1000)
            } else {
              reject(e)
            }
          }
        })
      }
      tryExport()
    })
    
    console.log('获取临时文件成功:', res)
    
    // 检查相册权限
    await ensureAlbumAuth()
    
    // 保存到相册
    uni.saveImageToPhotosAlbum({
      filePath: res.tempFilePath,
      success: () => {
        uni.hideLoading()
        uni.showToast({ title: '已保存到相册', icon: 'success' })
        console.log('保存到相册成功')
      },
      fail: (e) => {
        uni.hideLoading()
        console.error('保存到相册失败:', e)
        uni.showToast({ title: e?.errMsg || '保存失败', icon: 'none' })
      }
    })
  } catch (error) {
    uni.hideLoading()
    console.error('保存到相册过程出错:', error)
    if (error.message && error.message.includes('未授权')) {
      uni.showToast({ title: '未授权保存相册', icon: 'none' })
    } else {
      uni.showToast({ title: '保存失败：' + error.message, icon: 'none' })
    }
  }
}
</script>

<style lang="scss" scoped>
.poster-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  backdrop-filter: blur(8px);
}

.poster-panel {
  width: 90%;
  max-width: 700rpx;
  background: #fff;
  border-radius: 24rpx;
  padding: 40rpx 32rpx 32rpx 32rpx;
  box-shadow: 0 24rpx 80rpx rgba(0, 0, 0, 0.4);
  animation: slideIn 0.4s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(80rpx) scale(0.8);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.poster-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.poster-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 500rpx;
}

.poster-layout {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

.canvas-section {
  position: relative;
  flex-shrink: 0;
}

.debug-section {
  flex: 1;
  max-width: 300rpx;
}

/* 移除不需要的容器样式 */

.poster-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.poster-close {
  width: 60rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  font-size: 40rpx;
  color: #999;
  cursor: pointer;
}

.loading-container, .error-container {
  height: 500rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border-radius: 16rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.error-text {
  font-size: 28rpx;
  color: #e74c3c;
  text-align: center;
  margin-bottom: 20rpx;
}

.retry-btn {
  background: #1D428A;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 16rpx 32rpx;
  font-size: 24rpx;
}

/* 调试信息样式 */
/* 调试区域已注释，移除相关样式 */

.poster-canvas {
  width: 300px !important;
  height: 464px !important;
  display: block !important;
  background: #ffffff !important;
  border: 2rpx solid #e0e0e0 !important;
  border-radius: 16rpx;
  box-shadow: 0 12rpx 32rpx rgba(0, 0, 0, 0.15);
}

.poster-image {
  width: 300px;
  height: 464px;
  border-radius: 16rpx;
  border: 2rpx solid #e0e0e0;
  box-shadow: 0 12rpx 32rpx rgba(0, 0, 0, 0.15);
}

.btn-row {
  display: flex;
  justify-content: space-between;
  margin-top: 16rpx;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  margin: 0 12rpx;
  font-size: 30rpx;
  border-radius: 12rpx;
  border: none;
  transition: all 0.3s ease;
  font-weight: 500;
  
  &:disabled {
    opacity: 0.6;
    background: #e9ecef;
    color: #6c757d;
  }
  
  &:active {
    transform: scale(0.98);
  }
}

.primary {
  background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%);
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(33, 150, 243, 0.3);
  
  &:hover {
    box-shadow: 0 6rpx 16rpx rgba(33, 150, 243, 0.4);
  }
}

.test-buttons {
  display: flex;
  justify-content: space-around;
  margin: 16rpx 0;
}

.test-btn {
  background: #ff6b6b;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 12rpx 24rpx;
  font-size: 24rpx;
  margin: 0 8rpx;
}
</style>


